package com.iye.puretennis.fragment;

import android.annotation.SuppressLint;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.PopupMenu;
import com.iye.puretennis.R;
import com.iye.puretennis.custom.AccessCallBack;
import com.iye.puretennis.custom.ListItemAdapter;
import com.iye.puretennis.domain.GroupAccess;
import com.iye.puretennis.domain.ListItem;
import com.iye.puretennis.domain.UrlSuffix;
import com.iye.puretennis.domain.UserToken;
import com.iye.puretennis.helper.RemoteUrlCollections;
import com.iye.puretennis.helper.ServerAccessHelper;
import com.iye.puretennis.helper.Session;
import com.iye.puretennis.pulltorefresh.library.PullToRefreshBase;
import com.iye.puretennis.pulltorefresh.library.PullToRefreshListView;
import com.iye.puretennis.utils.StringUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.LinkedList;

/**
 * Author: Chuanbao on 2014/11/19.
 */
public class MyGroupsFragment extends TabFragment {

    public static final String TAG = "my_groups";

    private PullToRefreshListView groupsView;

    private LinkedList<ListItem> items = new LinkedList<ListItem>();

    private MyGroupsAdapter groupsAdapter;

    private int totalPages = 0;

    private int currentPageNumber = 1;


    @Override
    public int getViewId() {
        return R.layout.mygroups;
    }

    @Override
    public int getSourceId() {
        return R.id.my_groups;
    }

    @Override
    public boolean isParent() {
        return true;
    }


    private void loadGroups(final boolean refresh) {
        int newPageNumber = 1;
        if (!refresh) {
            newPageNumber = currentPageNumber;
        } else {
            items.clear();
        }
        final int finalNewPageNumber = newPageNumber;
        new Thread(new Runnable() {
            @Override
            public void run() {
                UserToken userToken = dbManager.retrieveCurrentUser();
                final String jsonStr = ServerAccessHelper.queryStringForGet(RemoteUrlCollections.getUrl(UrlSuffix.GROUPS) + "?currentPageNumber=" + finalNewPageNumber, userToken.getToken());
                if (StringUtils.hasText(jsonStr)) {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                JSONObject groupsJson = new JSONObject(jsonStr);
                                totalPages = groupsJson.getInt("totalPages");
                                currentPageNumber = groupsJson.getInt("currentPageNumber");
                                JSONArray groupsArrays = groupsJson.getJSONArray("groups");
                                for (int i = 0; i < groupsArrays.length(); i++) {
                                    JSONObject groupJson = groupsArrays.getJSONObject(i);
                                    String groupGuid = groupJson.getString("groupGuid");
                                    String groupName = groupJson.getString("groupName");
                                    boolean owner = groupJson.getBoolean("owner");
                                    String access = groupJson.getString("access");
                                    int requestAmount = groupJson.getInt("participantsAmount");
                                    ListItem listItem = new ListItem(groupGuid, groupName, owner, access, requestAmount);
                                    if (refresh) {
                                        items.add(listItem);
                                    } else {
                                        items.addLast(listItem);
                                    }
                                }

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            groupsView.onRefreshComplete();
                        }
                    });
                }
            }
        }).start();
    }

    @Override
    public void updateUI() {

        new Thread(new Runnable() {
            @Override
            public void run() {
                if (currentPageNumber > 1) {
                    //no need update,keep last updating data
                    return;
                }
                loadGroups(true);
            }
        }).start();
    }

    @Override
    public void onCustomCreateView(LayoutInflater inflater) {

        groupsView = (PullToRefreshListView) mainView.findViewById(R.id.my_groups_list);

        groupsAdapter = new MyGroupsAdapter(inflater, R.layout.mygroup_item, items);
        groupsView.setAdapter(groupsAdapter);
        groupsView.setLongClickable(true);

        groupsView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                loadGroups(true);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                if (currentPageNumber <= totalPages) {
                    loadGroups(false);
                } else {
                    groupsView.onRefreshComplete();
                }
            }
        });

        ImageButton addGroupButton = (ImageButton) mainView.findViewById(R.id.group_add);
        addGroupButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                goFragment(getSourceId(), SearchGroupFragment.TAG, SearchGroupFragment.class, null, false);

            }
        });

    }


    class MyGroupsAdapter extends ListItemAdapter {


        MyGroupsAdapter(LayoutInflater inflater, int resource, LinkedList<ListItem> items) {
            super(inflater, resource, items);
        }


        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            convertView = initial(position, convertView);

            final ListItem listItem = items.get(position);
            final int sourceId = getSourceId();

            viewCache.numberView.setText(listItem.getRequestAmount() + " 人");

            convertView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (GroupAccess.OWNER.name().equals(listItem.getAccess())) {
                        goFragment(sourceId, MyFriendsFragment.TAG, MyFriendsFragment.class, null, false);
                    } else {
                        putGroupGuidInSession(listItem);
                        if (listItem.isOwner()) {
                            goFragment(sourceId, MyGroupFragment.TAG, MyGroupFragment.class, null, false);
                        } else {
                            goFragment(sourceId, MyJoinedGroupFragment.TAG, MyJoinedGroupFragment.class, null, false);
                        }
                    }
                }
            });

            convertView.setOnLongClickListener(new View.OnLongClickListener() {

                @SuppressLint("ViewHolder")
                @Override
                public boolean onLongClick(View view) {
                    if (!GroupAccess.OWNER.name().equals(listItem.getAccess())) {
                        showPopupMenu(view, R.menu.details_delete_menu, new PopupMenu.OnMenuItemClickListener() {
                            @Override
                            public boolean onMenuItemClick(MenuItem menuItem) {

                                deleteGroup(listItem);
                                return true;
                            }
                        });
                    }
                    return true;
                }
            });
            return convertView;
        }
    }

    private void putGroupGuidInSession(ListItem listItem) {
        Session session = Session.newSession();
        session.put("groupGuid", listItem.getGuid());
    }

    private void deleteGroup(final ListItem listItem) {

        ServerAccessHelper.deleteGroup(listItem.getGuid(), token.getToken(), new AccessCallBack() {
            @Override
            public void doCallBack() {
                fragmentActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        items.remove(listItem);
                        groupsAdapter.notifyDataSetChanged();
                    }
                });
            }
        });
    }


}
